import os

config_file = os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir), "database/redis.conf")
redis_config_temp = ""
try:
    with open(config_file, "r") as f:
        redis_config_temp = f.read()
except:
    raise "Do not find redis configure file"

class RedisConf(object):
    
    def __init__(self):
        self.config = redis_config_temp
        self.escape_dict = {"'" : "\\'"}
    
    def handle_escape(self, str):
        new_str = ""
        for ch in str:
            new_str += self.escape_dict.get(ch, ch)
        
        return new_str
    
    def generate(self, pid_file, dir_path, log_file, db_file, port="", unix_socket=None):
        
        pid_file = "'" + self.handle_escape(pid_file) + "'"
        dir_path = "'" + self.handle_escape(dir_path) + "'"
        log_file = "'" + self.handle_escape(log_file) + "'"
        db_file = "'" + self.handle_escape(db_file) + "'"
        unix_socket = self.handle_escape(unix_socket)
        
        self.config = self.config.replace("#$$PIDFILE", "pidfile {}\n".format(pid_file))
        self.config = self.config.replace("#$$LOGFILE", "logfile {}\n".format(log_file))
        self.config = self.config.replace("#$$DIR", "dir {}\n".format(dir_path))
        self.config = self.config.replace("#$$DBFILENAME", "dbfilename {}\n".format(db_file))
        
            
        if unix_socket:
            self.config = self.config.replace("#$$UNIXSOCKET", "unixsocket {}\nunixsocketperm 755".format(unix_socket))
            port = 0
        
        if port >= 0:
            self.config = self.config.replace("#$$PORT", "port {}\n".format(str(port)))
        
            
        return self.config       
        